'''
__author__ = 'xxz'
__email__ = 'talos.tse@gmail.com'
Created on '2013/12/04 16:04'
'''

import urllib,Queue,sgmllib,re,os

class URLList(sgmllib.SGMLParser):
    def reset(self):
        sgmllib.SGMLParser.reset(self)
        self.URLqueue = Queue.Queue(maxsize = -1)
    def start_a(self,attrs):
        href = [v for k,v in attrs if k == 'href']
        if href:
            for u in href:
                pat = re.compile(r'http://(.+?)')
                if len(re.findall(pat,u)) == 0:
                    continue

                self.URLqueue.put(u)

def getURLList(url,parser):
    try:
        URLdata = urllib.urlopen(url)
        parser.feed(URLdata.read())
        URLdata.close()
    except:
        return

startURL = "http://www.qq.com"
parser = URLList()
getURLList(startURL,parser)

outfile = startURL[7:len(startURL)]+".txt"
out = open(outfile,'w+')


try:
    #BFS
    while parser.URLqueue.empty() == False:
        url = parser.URLqueue.get()
        print url
        out.writelines(url+'\n')
        getURLList(url,parser)
finally:
    parser.close()
    out.close()